package com.ruoyi.web.controller.order;

import com.alibaba.fastjson2.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.*;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.SmsTemplateCode;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.SmsUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.*;
import com.ruoyi.system.service.resp.RestaurantOrderDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: ruohao
 * @Date: 2023/9/2
 **/
@Api("订单")
@RestController
@RequestMapping("/order/normal")
public class NormalOrderController extends BaseController {
    @Resource
    private NormalExamineService normalExamineService;
    @Resource
    private NormalExamineDetailService normalExamineDetailService;
    @Resource
    private RestaurantBalanceService restaurantBalanceService;
    @Resource
    private RestaurantOrderService restaurantOrderService;
    @Resource
    private RestaurantOrderDetailMapper restaurantOrderDetailMapper;
    @Resource
    private NormalExamineMapper normalExamineMapper;
    @Resource
    private NormalMapper normalMapper;
    @Resource
    private ReplaceMapper replaceMapper;
    @Resource
    private BuffetMapper buffetMapper;
    @Resource
    private BuffetExamineMapper buffetExamineMapper;
    @Resource
    private RestaurantCustomerService restaurantCustomerService;
    @Resource
    private NormalService normalService;
    @Resource
    private ReplaceService replaceService;
    @Resource
    private RestaurantGoodsService restaurantGoodsService;
    @Resource
    private RestaurantStoreResourceService restaurantStoreResourceService;
    @Resource
    private NormalOrderDetailController normalOrderDetailController;
    @Resource
    private CustomerAddressMapper customerAddressMapper;
    @Resource
    private RestaurantOrderMapper restaurantOrderMapper;
    @Resource
    private SysUserMapper sysUserMapper;

    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @GetMapping("/listTodayOrder")
    public TableDataInfo listTodayOrder() {
        RestaurantOrder query = new RestaurantOrder();
//        Map<String, Object> filter = new HashMap<>();
//        filter.put("beginTime", TimeUtils.getTodayBegin());
//        query.setParams(filter);
        List<RestaurantOrder> list = restaurantOrderMapper.selectTodayList(query);
        list.forEach(r -> {
            List<RestaurantOrderDetail> details = restaurantOrderDetailMapper.selectList(RestaurantOrderDetail.builder().orderId(r.getId()).build());
            if (CollectionUtils.isEmpty(details)) {
                logger.warn("获取今日订单 订单详情为空 业务不正常");
                r.setAmount(new BigDecimal(0));
                r.setPeopleCount(1);
                return;
            }
            r.setAmount(getTotalPrice(details));
            if (!StringUtils.isBlank(r.getType()) && r.getType().contains("自助")) {
                r.setPeopleCount(details.get(0).getCount());
            } else {
                r.setPeopleCount(1);
            }
        });
        return getDataTable(list);
    }

    @ApiOperation("获取订单 分页")
    @Log(title = "网上订单", businessType = BusinessType.OTHER)
    @GetMapping("/list")
    public TableDataInfo list(RestaurantOrder restaurantOrder) {
        if ("pc".equals(restaurantOrder.getAppSource())) {
            startPage();
            List<RestaurantOrder> list = restaurantOrderService.getNormalOrderList(restaurantOrder);
            return getDataTable(pcFillOrderInfo(list));
        }
        // 点餐购物车
        if ("normal".equals(restaurantOrder.getAppSource())) {
            restaurantOrder.setStatus("购物车");
            restaurantOrder.setCustomerId(SecurityUtils.getUserId());
            List<RestaurantOrder> list = restaurantOrderService.getNormalOrderList(restaurantOrder);
            return getDataTable(fillToDTO(list, restaurantOrder.getType()));
        }
        // 代购购物车
        if ("replace".equals(restaurantOrder.getAppSource())) {
            restaurantOrder.setStatus("购物车");
            restaurantOrder.setCustomerId(SecurityUtils.getUserId());
            List<RestaurantOrder> list = restaurantOrderService.getNormalOrderList(restaurantOrder);
            return getDataTable(fillToDTO(list, restaurantOrder.getType()));
        }
        startPage();
        // h5全部场景
        List<RestaurantOrder> list;
        if (!"order".equals(restaurantOrder.getAppSource())) {
            restaurantOrder.setCustomerId(SecurityUtils.getUserId());
        }
        if ("待付款".equals(restaurantOrder.getStatus())) {
            restaurantOrder.setCustomerId(SecurityUtils.getUserId());
            restaurantOrder.setStatus("待付款");
        }
        if ("已完成".equals(restaurantOrder.getStatus())) {
            restaurantOrder.setCustomerId(SecurityUtils.getUserId());
            restaurantOrder.setStatus("已送达");
        }
        if ("进行中".equals(restaurantOrder.getStatus())) {
            restaurantOrder.setCustomerId(SecurityUtils.getUserId());
            list = restaurantOrderService.getOnGoingNormalOrderList(restaurantOrder);
            return getDataTable(fillToDTO(list, restaurantOrder.getType()));
        }

        list = restaurantOrderService.getNormalOrderList(restaurantOrder);
        return getDataTable(fillToDTO(list, restaurantOrder.getType()));
    }

    @ApiOperation("获取购物车")
    @Log(title = "网上订单", businessType = BusinessType.OTHER)
    @GetMapping("/cart")
    public TableDataInfo cart(RestaurantOrder restaurantOrder) {
        restaurantOrder.setStatus("购物车");
        List<RestaurantOrder> list = restaurantOrderService.getNormalOrderList(restaurantOrder);
        return getDataTable(fillToDTO(list, restaurantOrder.getType()));
    }

    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable Long id) {
        return success((restaurantOrderService.selectNormalOrderById(id)));
    }

    @ApiOperation("增加订单")
    @Log(title = "新增订单", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@Validated @RequestBody RestaurantOrder restaurantOrder) {

        String area = restaurantOrder.getArea();
        if (restaurantOrder == null || StringUtils.isBlank(area)) {
            area = SecurityUtils.getUserLocation();
        }
        if (StringUtils.isBlank(area) || area.equals("全部")) {
            throw new BaseException("该用户园区为全部,不能新增");
        }
        restaurantOrder.setArea(area);

        restaurantOrder.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        if (!"pc".equals(restaurantOrder.getAppSource())) {
            restaurantOrder.setCustomerId(SecurityUtils.getUserId());
        }
        //新增的时候删除多余的
        RestaurantOrder query = new RestaurantOrder();
        query.setArea(area);
        query.setCustomerId(SecurityUtils.getUserId());
        query.setStatus("购物车");
        List<RestaurantOrder> list = restaurantOrderService.getNormalOrderList(query);
        for (RestaurantOrder order : list) {
            restaurantOrderService.deleteNormalOrderById(order.getId());
        }

        Boolean result = restaurantOrderService.createNormalOrder(restaurantOrder);
        if (!result) {
            return error();
        }
        restaurantOrder.setOrderNum(restaurantOrder.getId() == null ? "" : restaurantOrder.getId().toString());
        restaurantOrderService.updateNormalOrder(restaurantOrder);

        if ("购物车".equals(restaurantOrder.getStatus())) {
            return success();
        }
        restaurantOrder.setStatus("待确定");
        if ("自助餐桌餐订单".equals(restaurantOrder.getType())) {
            handleBuffet(restaurantOrder);
        } else if ("点餐桌餐订单".equals(restaurantOrder.getType())) {
            handleBookNormal(restaurantOrder);
        } else if ("点餐网上订单".equals(restaurantOrder.getType())) {
            handleOnlineNormal(restaurantOrder);
        } else if ("代购订单".equals(restaurantOrder.getType())) {
            sendMess(restaurantOrder);
        }
        return success();
    }

    private void sendMess(RestaurantOrder restaurantOrder) {
        //给副科长和收银员发短信  app订单 点餐网上订单 和 代购订单
        try {
            String area = restaurantOrder.getArea();
            List<String> longs = sysUserMapper.getFKZAndSYY(area);
            for (String aLong : longs) {
                if (StringUtils.isNotBlank(aLong)) {
                    SmsUtils.sendSms(SmsTemplateCode.ORDER.getCode(), aLong, "");
                }
            }
        } catch (Exception e) {

        }
    }

    private void handleOnlineNormal(RestaurantOrder restaurantOrder) {
        NormalExamine normalExamine = new NormalExamine();
        normalExamine.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        normalExamine.setOrderId(restaurantOrder.getId());
        normalExamineMapper.insert(normalExamine);

        sendMess(restaurantOrder);
    }

    private void handleBookNormal(RestaurantOrder restaurantOrder) {
        NormalExamine normalExamine = new NormalExamine();
        normalExamine.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        normalExamine.setOrderId(restaurantOrder.getId());
        normalExamineMapper.insert(normalExamine);
    }

    private void handleBuffet(RestaurantOrder restaurantOrder) {
        return;
    }

    @ApiOperation("编辑订单")
    @Log(title = "编辑订单", businessType = BusinessType.UPDATE)
    @PutMapping
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult edit(@Validated @RequestBody RestaurantOrder restaurantOrder) {
        if (restaurantOrder.getCustomerInfoId() != null) {
            CustomerAddress customerAddress = customerAddressMapper.selectById(restaurantOrder.getCustomerInfoId());
            if (customerAddress != null) {
                restaurantOrder.setAddress(customerAddress.getAddress());
                restaurantOrder.setCustomerName(customerAddress.getName());
                restaurantOrder.setPhone(customerAddress.getPhone());
            }
        }
        RestaurantOrder oldOrder = restaurantOrderService.selectNormalOrderById(restaurantOrder.getId());
        if (oldOrder.getStatus().equals("已送达")) {
            throw new BaseException("已送达的订单不允许修改");
        }
        if ("已送达".equals(restaurantOrder.getStatus()) && !"已送达".equals(oldOrder.getStatus())) {
//            processStoreOut(restaurantOrder.getId());
        }
        if ("待付款".equals(oldOrder.getStatus())
                && "待确定".equals(restaurantOrder.getStatus())
                && "点餐网上订单".equals(oldOrder.getType())) {
            restaurantOrder.setCustomerId(SecurityUtils.getUserId());
            changeUserBalance(restaurantOrder.getId(), restaurantOrder);
            handleOnlineNormal(restaurantOrder);
        }
        if ("待付款".equals(oldOrder.getStatus())
                && "待确定".equals(restaurantOrder.getStatus())) {
            changeUserBalance(restaurantOrder.getId(), restaurantOrder);

            //app新增订单是掉的修改方法 。。。。无语
            if ("代购订单".equals(restaurantOrder.getType())) {
                sendMess(restaurantOrder);
            }
        }

        restaurantOrder.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        Boolean result = restaurantOrderService.updateNormalOrder(restaurantOrder);
        if (result) {
            normalOrderDetailController.handleExamine(restaurantOrder.getId());
            return success();
        }
        return error();
    }

    @Resource
    private StoreOutMapper storeOutMapper;

    @Resource
    private StoreOutDetailMapper storeOutDetailMapper;

    @Resource
    private RestaurantGoodsDetailMapper restaurantGoodsDetailMapper;

    private void processStoreOut(Long orderId) {
        try {
            List<RestaurantOrderDetail> details = restaurantOrderDetailMapper.selectList(RestaurantOrderDetail.builder().orderId(orderId).build());
            if (CollectionUtils.isEmpty(details)) {
                return;
            }
            if (isBuffet(details)) {
                return;
            }
            StoreOut storeOut = new StoreOut();
            storeOut.setOrderId(orderId);
            storeOut.setType("订单出库");
//            storeOut.setArea();
            //领用人 厨师长
            storeOut.setApplicant(sysUserMapper.getNickNameByPost());
            int result = storeOutMapper.insert(storeOut);
            if (result != 1) {
                throw new ServiceException(String.format("创建订单出库失败 %s", JSON.toJSONString(storeOut)));
            }
            List<StoreOutDetail> storeOutDetails = getStoreOutDetails(details, storeOut.getId());
            if (CollectionUtils.isEmpty(storeOutDetails)) {
                return;
            }
            for (StoreOutDetail storeOutDetail : storeOutDetails) {
                storeOutDetailMapper.insert(storeOutDetail);
            }
        } catch (Exception e) {
            logger.error("处理订单出库失败", e);
        }
    }

    private List<StoreOutDetail> getStoreOutDetails(List<RestaurantOrderDetail> details, Long outId) {
        List<StoreOutDetail> result = new ArrayList<>();
        Map<Long, StoreOutDetail> storeOutDetailMap = new HashMap<>();
        for (RestaurantOrderDetail detail : details) {
            if (detail == null || detail.getCount() == null || detail.getCount() == 0) {
                continue;
            }
            Long normalId = detail.getNormalId();
            if (normalId != null) {
                Normal normal = normalMapper.selectById(normalId);
                if (normal.getGoodsId() == null) {
                    continue;
                }
                RestaurantGoods goods = restaurantGoodsService.selectById(normal.getGoodsId());
                if (goods == null) {
                    continue;
                }
                List<RestaurantGoodsDetail> restaurantGoodsDetails = restaurantGoodsDetailMapper.selectRestaurantGoodsDetailList(RestaurantGoodsDetail.builder().goodsId(goods.getId()).build());
                if (CollectionUtils.isEmpty(restaurantGoodsDetails)) {
                    continue;
                }
                for (RestaurantGoodsDetail goodsDetail : restaurantGoodsDetails) {
                    Long resourceId = goodsDetail.getResourceId();
                    StoreOutDetail storeOutDetail = storeOutDetailMap.get(resourceId);
                    if (storeOutDetail == null) {
                        storeOutDetail = new StoreOutDetail();
                        storeOutDetail.setResourceId(resourceId);
                        storeOutDetail.setAmount(BigDecimal.ZERO);
                        storeOutDetail.setOutId(outId);
                        storeOutDetailMap.put(resourceId, storeOutDetail);
                        result.add(storeOutDetail);
                    }
                    storeOutDetail.setAmount(storeOutDetail.getAmount().add(new BigDecimal(goodsDetail.getAmount() * detail.getCount())));
                }
            }
        }
        return result;
    }

    private boolean isBuffet(List<RestaurantOrderDetail> details) {
        for (RestaurantOrderDetail detail : details) {
            if (detail == null) {
                continue;
            }
            if (detail.getBuffetId() != null) {
                return true;
            }
        }
        return false;
    }

    private void changeUserBalance(Long orderId, RestaurantOrder order) {
        if (orderId == null) {
            return;
        }
        RestaurantCustomer restaurantCustomer = restaurantCustomerService.getCustomerByUserId(String.valueOf(SecurityUtils.getUserId()));
        if (restaurantCustomer == null) {
            return;
        }
        List<RestaurantOrderDetail> orderDetails = restaurantOrderDetailMapper.selectList(RestaurantOrderDetail.builder().orderId(orderId).build());
        if (CollectionUtils.isEmpty(orderDetails)) {
            return;
        }
        BigDecimal totalPrice = getTotalPrice(orderDetails);
        RestaurantCustomer update = new RestaurantCustomer();
        update.setId(restaurantCustomer.getId());
        //上次金额-在方法外面修改
        order.setLastMoney(update.getBalance());
        //扣费
        update.setBalance(restaurantCustomer.getBalance().subtract(totalPrice));
        //本次金额
        order.setNowMoney(update.getBalance());
        restaurantCustomerService.comsumeCustomerBalance(SecurityUtils.getUserId(), totalPrice, "订单" + orderId + "扣除", SecurityUtils.getLoginUser().getUser());
    }

    @Transactional(rollbackFor = Exception.class)
    @Log(title = "网上订单All", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id) {
        NormalExamine normalExamines = normalExamineService.selectByOrderId(id);
        if (normalExamines != null) {
            normalExamineService.deleteById(normalExamines.getId());

            NormalExamineDetail query = new NormalExamineDetail();
            query.setExamineId(normalExamines.getId());
            List<NormalExamineDetail> details = normalExamineDetailService.selectList(query);
            for (NormalExamineDetail detail : details) {
                normalExamineDetailService.deleteById(detail.getId());
            }
        }
        RestaurantOrder order = restaurantOrderService.selectNormalOrderById(id);
        if (order != null && StringUtils.isNotBlank(order.getStatus()) && order.getStatus().equals("已送达")) {
            throw new BaseException("已送达的订单不允许删除");
        }


        return toAjax(restaurantOrderService.deleteNormalOrderById(id));
    }

    @Transactional(rollbackFor = Exception.class)
    @Log(title = "网上订单All", businessType = BusinessType.DELETE)
    @GetMapping("/cancel/{id}")
    public AjaxResult cancel(@PathVariable Long id) {
        RestaurantOrder order = restaurantOrderService.selectNormalOrderById(id);
        if (order != null && StringUtils.isNotBlank(order.getStatus()) && order.getStatus().equals("已送达")) {
            throw new BaseException("已送达的订单不允许取消");
        }
        List<RestaurantOrderDetail> restaurantOrderDetails = restaurantOrderDetailMapper.selectList(RestaurantOrderDetail.builder()
                .orderId(order.getId())
                .build());
        List<String> strings = Arrays.asList("待确定", "已接单", "制作中", "送餐中");
        if (strings.contains(order.getStatus())) {
            //退钱 并增加消费明细
            RestaurantCustomer customer = restaurantCustomerService.getCustomerByUserId(order.getCustomerId().toString());
            BigDecimal amount = BigDecimal.ZERO;
            amount = getTotalPrice(restaurantOrderDetails);
            customer.setBalance(customer.getBalance().add(amount));
            restaurantCustomerService.updateCustomerByUserId(customer);

            //创建消费记录
            RestaurantBalanceDetail restaurantBalanceDetail = new RestaurantBalanceDetail();
            restaurantBalanceDetail.setType("手动增加");
            restaurantBalanceDetail.setLocation(SecurityUtils.getUserLocation());
            restaurantBalanceDetail.setAmount(amount);
            restaurantBalanceDetail.setCustomerId(order.getCustomerId());
            restaurantBalanceDetail.setCreateBy(SecurityUtils.getNickName());
            if ("normal".equals(order.getType())) {
                restaurantBalanceDetail.setReason("点餐订单[" + order.getOrderNum() + "]取消并退款");
            } else if ("buffet".equals(order.getType())) {
                restaurantBalanceDetail.setReason("自助餐订单[" + order.getOrderNum() + "]取消并退款");
            } else if ("replace".equals(order.getType())) {
                restaurantBalanceDetail.setReason("代购订单[" + order.getOrderNum() + "]取消并退款");
            } else if ("点餐网上订单".equals(order.getType())) {
                restaurantBalanceDetail.setReason("点餐网上订单[" + order.getOrderNum() + "]取消并退款");
            } else if ("自助餐餐桌订单".equals(order.getType())) {
                restaurantBalanceDetail.setReason("自助餐餐桌订单[" + order.getOrderNum() + "]取消并退款");
            } else if ("代购订单".equals(order.getType())) {
                restaurantBalanceDetail.setReason("代购订单[" + order.getOrderNum() + "]取消并退款");
            }
            restaurantBalanceService.create(restaurantBalanceDetail);

        } else {
            throw new BaseException("该单据状态不为" + strings + "无法取消");
        }

        //把质检单也取消
        NormalExamine normalExamine = normalExamineMapper.selectByOrderId(order.getId());
        if (normalExamine != null) {
            normalExamine.setStatus("取消");
            normalExamineMapper.update(normalExamine);
        }

        order.setStatus("取消");
        restaurantOrderService.updateNormalOrder(order);
        return AjaxResult.success();
    }

    @Transactional(rollbackFor = Exception.class)
    @Log(title = "网上订单refund", businessType = BusinessType.DELETE)
    @GetMapping("/refund/{id}")
    public AjaxResult refund(@PathVariable Long id) {
        //退款
        RestaurantOrder order = restaurantOrderService.selectNormalOrderById(id);
        if (order != null && StringUtils.isNotBlank(order.getStatus()) && !order.getStatus().equals("已送达")) {
            throw new BaseException("只有已送达的订单才可以退款");
        }

        //退钱 并增加消费明细
        RestaurantCustomer customer = restaurantCustomerService.getCustomerByUserId(order.getCustomerId().toString());
        customer.setBalance(customer.getBalance().add(order.getAmount()));
        restaurantCustomerService.updateCustomerByUserId(customer);

        //创建消费记录
        RestaurantBalanceDetail restaurantBalanceDetail = new RestaurantBalanceDetail();
        restaurantBalanceDetail.setType("手动退款");
        restaurantBalanceDetail.setLocation(SecurityUtils.getUserLocation());
        restaurantBalanceDetail.setAmount(order.getAmount());
        restaurantBalanceDetail.setCustomerId(order.getCustomerId());
        restaurantBalanceDetail.setCreateBy(SecurityUtils.getNickName());
        if ("normal".equals(order.getType())) {
            restaurantBalanceDetail.setReason("点餐订单[" + order.getOrderNum() + "]手动退款");
        } else if ("buffet".equals(order.getType())) {
            restaurantBalanceDetail.setReason("自助餐订单[" + order.getOrderNum() + "]手动退款");
        } else if ("replace".equals(order.getType())) {
            restaurantBalanceDetail.setReason("代购订单[" + order.getOrderNum() + "]手动退款");
        } else if ("点餐网上订单".equals(order.getType())) {
            restaurantBalanceDetail.setReason("点餐网上订单[" + order.getOrderNum() + "]手动退款");
        } else if ("自助餐餐桌订单".equals(order.getType())) {
            restaurantBalanceDetail.setReason("自助餐餐桌订单[" + order.getOrderNum() + "]手动退款");
        } else if ("代购订单".equals(order.getType())) {
            restaurantBalanceDetail.setReason("代购订单[" + order.getOrderNum() + "]手动退款");
        }
        restaurantBalanceService.create(restaurantBalanceDetail);

        order.setStatus("已退款");
        order.setUpdateBy(SecurityUtils.getNickName());
        order.setUpdateTime(new Date());
        restaurantOrderService.updateNormalOrder(order);
        return AjaxResult.success();
    }


    private List<RestaurantOrderDTO> fillToDTO(List<RestaurantOrder> restaurantOrders, String type) {
        if (CollectionUtils.isEmpty(restaurantOrders)) {
            return new ArrayList<>();
        }
        List<Long> orderId = restaurantOrders.stream().map(RestaurantOrder::getId).collect(Collectors.toList());

        Map<Long, NormalExamine> restaurantGoodsMap = normalExamineService.selectByIds(orderId).stream().collect(Collectors.toMap(NormalExamine::getOrderId, g -> g));
        List<RestaurantOrderDTO> restaurantOrderDTOS = restaurantOrders.stream().map(g -> {
            RestaurantOrderDTO restaurantOrderDTO = new RestaurantOrderDTO();
            restaurantOrderDTO.setId(g.getId());
            restaurantOrderDTO.setOrderTime(getFormatTime(g.getOrderTime()));
            restaurantOrderDTO.setCustomerId(g.getCustomerId());
            restaurantOrderDTO.setType(g.getType());
            restaurantOrderDTO.setExtra(g.getExtra());
            restaurantOrderDTO.setAddress(g.getAddress());
            restaurantOrderDTO.setPhone(g.getPhone());
            restaurantOrderDTO.setStatus(g.getStatus());
            restaurantOrderDTO.setComment(g.getComment());
            restaurantOrderDTO.setCreateBy(g.getCreateBy());
            restaurantOrderDTO.setCreateTime(g.getCreateTime());
            restaurantOrderDTO.setUpdateBy(g.getUpdateBy());
            restaurantOrderDTO.setUpdateTime(g.getUpdateTime());
            restaurantOrderDTO.setRemark(g.getRemark());
            restaurantOrderDTO.setPhone(g.getPhone());
            restaurantOrderDTO.setAddress(g.getAddress());
            restaurantOrderDTO.setArea(g.getArea());
            restaurantOrderDTO.setCustomerName(g.getCustomerName());
            restaurantOrderDTO.setSendTime(getFormatTime(g.getSendTime()));
            restaurantOrderDTO.setLastMoney(g.getLastMoney());
            restaurantOrderDTO.setNowMoney(g.getNowMoney());
            restaurantOrderDTO.setOrderStatus(Optional.ofNullable(restaurantGoodsMap.get(g.getId())).map(NormalExamine::getStatus).orElse("未查询到质检单"));
            fillAmount(restaurantOrderDTO, g.getId());
            fillExamine(restaurantOrderDTO, g.getId());
            return restaurantOrderDTO;
        }).collect(Collectors.toList());
        PageInfo<RestaurantOrder> oldPage = new PageInfo<>(restaurantOrders);
        Page<RestaurantOrderDTO> newPage = new Page<>();
        newPage.addAll(restaurantOrderDTOS);
        newPage.setTotal(oldPage.getTotal());
        return newPage;
    }

    private List<RestaurantOrderDTO> pcFillOrderInfo(List<RestaurantOrder> restaurantOrders) {
        if (CollectionUtils.isEmpty(restaurantOrders)) {
            return new ArrayList<>();
        }
        List<Long> orderId = restaurantOrders.stream().map(RestaurantOrder::getId).collect(Collectors.toList());
        List<SysUser> customerInfos = sysUserMapper.selectUserByUserIds(restaurantOrders.stream().map(RestaurantOrder::getCustomerId).toArray(Long[]::new));
        Map<Long, SysUser> customerIdInfoMap = customerInfos.stream().collect(Collectors.toMap(SysUser::getUserId, s -> s));
        Map<Long, NormalExamine> restaurantGoodsMap = normalExamineService.selectByIds(orderId).stream().collect(Collectors.toMap(NormalExamine::getOrderId, g -> g));
        List<RestaurantOrderDTO> restaurantOrderDTOS = restaurantOrders.stream().map(g -> {
            RestaurantOrderDTO restaurantOrderDTO = new RestaurantOrderDTO();
            restaurantOrderDTO.setId(g.getId());
            restaurantOrderDTO.setOrderTime(getFormatTime(g.getOrderTime()));
            restaurantOrderDTO.setCustomerId(g.getCustomerId());
            restaurantOrderDTO.setType(g.getType());
            restaurantOrderDTO.setExtra(g.getExtra());
            restaurantOrderDTO.setAddress(g.getAddress());
            restaurantOrderDTO.setPhone(g.getPhone());
            restaurantOrderDTO.setStatus(g.getStatus());
            restaurantOrderDTO.setComment(g.getComment());
            restaurantOrderDTO.setCreateBy(g.getCreateBy());
            restaurantOrderDTO.setCreateTime(g.getCreateTime());
            restaurantOrderDTO.setUpdateBy(g.getUpdateBy());
            restaurantOrderDTO.setUpdateTime(g.getUpdateTime());
            restaurantOrderDTO.setRemark(g.getRemark());
            restaurantOrderDTO.setPhone(g.getPhone());
            restaurantOrderDTO.setAddress(g.getAddress());
            restaurantOrderDTO.setArea(g.getArea());
            restaurantOrderDTO.setLastMoney(g.getLastMoney());
            restaurantOrderDTO.setNowMoney(g.getNowMoney());
            restaurantOrderDTO.setCustomerName(Optional.ofNullable(customerIdInfoMap.get(g.getCustomerId())).map(SysUser::getNickName).orElse(null));
            restaurantOrderDTO.setSendTime(getFormatTime(g.getSendTime()));
            restaurantOrderDTO.setOrderStatus(Optional.ofNullable(restaurantGoodsMap.get(g.getId())).map(NormalExamine::getStatus).orElse("未查询到质检单"));
            fillAmount(restaurantOrderDTO, g.getId());
            fillExamine(restaurantOrderDTO, g.getId());
            return restaurantOrderDTO;
        }).collect(Collectors.toList());
        PageInfo<RestaurantOrder> oldPage = new PageInfo<>(restaurantOrders);
        Page<RestaurantOrderDTO> newPage = new Page<>();
        newPage.addAll(restaurantOrderDTOS);
        newPage.setTotal(oldPage.getTotal());
        return newPage;
    }

    private String getFormatTime(Date time) {
        if (time == null) {
            return null;
        }
        return sdf.format(time);
    }

    private void fillAmount(RestaurantOrderDTO restaurantOrderDTO, Long orderId) {
        PageUtils.clearPage();
        List<RestaurantOrderDetail> restaurantOrderDetails = restaurantOrderDetailMapper.selectList(RestaurantOrderDetail.builder()
                .orderId(orderId)
                .build());
        if (CollectionUtils.isEmpty(restaurantOrderDetails)) {
            restaurantOrderDTO.setAmount(new BigDecimal(0));
            restaurantOrderDTO.setCount(0);
            restaurantOrderDTO.setImages("");
        } else {
            restaurantOrderDTO.setAmount(getTotalPrice(restaurantOrderDetails));
            restaurantOrderDTO.setCount(getTotalCount(restaurantOrderDetails));
            restaurantOrderDTO.setImages(getImages(restaurantOrderDetails));
        }
    }

    private String getImages(List<RestaurantOrderDetail> orderDetails) {
        StringBuilder imagesBuilder = new StringBuilder();
        for (RestaurantOrderDetail detail : orderDetails) {
            if (detail == null) {
                continue;
            }
            if (detail.getNormalId() != null) {
                Normal normal = normalService.selectById(detail.getNormalId());
                if (normal == null) {
                    continue;
                }
                RestaurantGoods restaurantGoods = restaurantGoodsService.selectById(normal.getGoodsId());
                if (restaurantGoods == null) {
                    continue;
                }
                if (StringUtils.isBlank(restaurantGoods.getImage())) {
                    continue;
                }
                String[] images = restaurantGoods.getImage().split(",");
                if (images.length == 0) {
                    continue;
                }
                imagesBuilder.append(images[0]);
                imagesBuilder.append(",");
            } else if (detail.getReplaceId() != null) {
                Replace replace = replaceService.selectById(detail.getReplaceId());
                if (replace == null) {
                    continue;
                }
                RestaurantStoreResource resource = restaurantStoreResourceService.selectRestaurantStoreResourceById(replace.getResourceId());
                if (resource == null) {
                    continue;
                }
                if (StringUtils.isBlank(resource.getImageUrl())) {
                    continue;
                }
                String[] images = resource.getImageUrl().split(",");
                if (images.length == 0) {
                    continue;
                }
                imagesBuilder.append(images[0]);
                imagesBuilder.append(",");
            }
        }
        return imagesBuilder.toString();
    }

    private Integer getTotalCount(List<RestaurantOrderDetail> orderDetails) {
        int count = 0;
        for (RestaurantOrderDetail detail : orderDetails) {
            if (detail == null) {
                continue;
            }
            Integer cnt = Optional.ofNullable(detail.getCount()).orElse(0);
            count = cnt + count;
        }
        return count;
    }


    private BigDecimal getTotalPrice(List<RestaurantOrderDetail> orderDetails) {
        BigDecimal amount = new BigDecimal(0);
        for (RestaurantOrderDetail detail : orderDetails) {
            if (detail == null) {
                continue;
            }
            Integer cnt = Optional.ofNullable(detail.getCount()).orElse(0);
            if (cnt == 0) {
                continue;
            }
            if (detail.getNormalId() != null) {
                Normal normal = normalMapper.selectById(detail.getNormalId());
                if (normal != null && normal.getPrice() != null) {
                    amount = amount.add(normal.getPrice().multiply(new BigDecimal(cnt)));
                }
            } else if (detail.getBuffetId() != null) {
                Buffet buffet = buffetMapper.selectById(detail.getBuffetId());
                if (buffet != null && buffet.getPrice() != null) {
                    amount = amount.add(buffet.getPrice().multiply(new BigDecimal(cnt)));
                }
            } else if (detail.getReplaceId() != null) {
                Replace replace = replaceMapper.selectById(detail.getReplaceId());
                if (replace != null && replace.getPrice() != null) {
                    amount = amount.add(replace.getPrice().multiply(new BigDecimal(cnt)));
                }
            }
        }
        return amount;
    }

    private void fillExamine(RestaurantOrderDTO restaurantOrderDTO, Long orderId) {
        if (restaurantOrderDTO.getType() == null || !restaurantOrderDTO.getType().contains("点餐")) {
            return;
        }
        NormalExamine normalExamine = normalExamineService.selectByOrderId(orderId);
        if (normalExamine == null) {
            return;
        }
        List<NormalExamineDetail> normalExamineDetails = normalExamineDetailService.selectList(NormalExamineDetail.builder()
                .examineId(normalExamine.getId()).build());

        if (CollectionUtils.isEmpty(normalExamineDetails)) {
            restaurantOrderDTO.setExamineStatus("无订单明细");
            return;
        }

        Integer okCnt = 0;
        Integer failCnt = 0;
        Integer waitCnt = 0;
        for (NormalExamineDetail detail : normalExamineDetails) {
            if (detail == null) {
                continue;
            }
            if (StringUtils.isBlank(detail.getPlateStatus())
                    && StringUtils.isBlank(detail.getResourceStatus())) {
                waitCnt = waitCnt + 1;
            } else if ("否".equals(detail.getPlateStatus())
                    || "否".equals(detail.getResourceStatus())) {
                failCnt = failCnt + 1;
            } else if ("是".equals(detail.getPlateStatus())
                    && "是".equals(detail.getResourceStatus())) {
                okCnt = okCnt + 1;
            }
        }
        if (failCnt > 0) {
            restaurantOrderDTO.setExamineStatus("质检不合格");
        } else if (okCnt.equals(normalExamineDetails.size())) {
            restaurantOrderDTO.setExamineStatus("质检合格");
        } else {
            restaurantOrderDTO.setExamineStatus("质检待完成");
        }
        restaurantOrderDTO.setExamineId(normalExamine.getId());

        if (StringUtils.isNotBlank(normalExamine.getStatus()) && normalExamine.getStatus().equals("取消")) {
            restaurantOrderDTO.setExamineStatus("取消");
        }
    }
}
